package com.letcoding.html2image.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

/**
 * @ClassName FreeMarkerUtil
 * @Description FreeMarker工具类
 * @Author will
 * @Date 2020/8/24 15:51
 */
public class FreeMarkerUtil {

    /**
     * 根据传入的FreeMark的模板名解析成字符串
     * @param data            数据对象
     * @param htmlName        模板名 eg:bill.html
     * @return
     */
    public static String freeMarkerRenderByHtml(Object data, String htmlName) {
        Writer stringWriter = new StringWriter();
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
            cfg.setClassForTemplateLoading(FreeMarkerUtil.class,"/static");
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);
            cfg.setWrapUncheckedExceptions(true);
            Template temp = cfg.getTemplate(htmlName);
            temp.process(data, stringWriter);
            stringWriter.flush();
            return stringWriter.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                stringWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 根据传入的FreeMark的模板名解析成字符串
     * @param data            数据对象
     * @param ftlName        模板名 eg:bill.ftl
     * @return
     */
    public static String freeMarkerRender(Object data, String ftlName) {
        Writer stringWriter = new StringWriter();
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
            cfg.setClassForTemplateLoading(FreeMarkerUtil.class,"/template");
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);
            cfg.setWrapUncheckedExceptions(true);
            Template temp = cfg.getTemplate(ftlName);
            temp.process(data, stringWriter);
            stringWriter.flush();
            return stringWriter.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                stringWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
